package com.forlgb.powercloud.netty4.all.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Properties;

import static com.forlgb.powercloud.netty4.all.common.util.PropertiesUtils.getProperties;

@Slf4j
public class FileUploadServer {

    private static int port;

    /**
     * 服务端监听端口
     *
     * @param port
     */
    public void bind(int port) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel channel) throws Exception {
                    log.info("客户端连接中:" + channel.localAddress().toString());
                    channel.pipeline().addLast(new ObjectEncoder());
                    channel.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.weakCachingConcurrentResolver(null)));
                    channel.pipeline().addLast(new FileUploadServerHandler());
                }
            });
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            log.info("服务端等待中");
            channelFuture.channel().closeFuture().sync();
            log.info("文件传输结束");
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws IOException {
        setBasicData();
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        try{
            new FileUploadServer().bind(port);
        }catch (NumberFormatException | InterruptedException e){
            e.printStackTrace();
        }
    }

    private static void setBasicData() throws IOException {
        Properties properties = getProperties("/server.properties");
        port = Integer.valueOf(String.valueOf(properties.get("tcp.server.port")));
    }
}
